package panda.client.ui.widgets;

import panda.client.engine.Observable;
import panda.client.engine.Observer;
import panda.client.enumerations.ZIndexLevel;
import panda.client.ui.observable.ObservableLastMousedCard;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;

/**
 * Manages zooming of DraggableCards on Panda.canvas. Observes LastMousedCard.java and whenever it updates, ZoomManager
 * updates the card being zoomed in on.
 * 
 * @author zane.tian@gmail.com
 */
public class ZoomManager implements Observer {
	private final PopupPanel popup;
	private boolean zooming;
	private Image cardBackImg;

	public ZoomManager(ObservableLastMousedCard card) {
		cardBackImg = new Image("img/cardback/cardback-100.jpg");
		
		popup = new PopupPanel();
		DOM.setStyleAttribute(popup.getElement(), "zIndex", String.valueOf(ZIndexLevel.ZOOMCARD.getZIndex()));
		popup.add(cardBackImg);
		popup.setGlassEnabled(true); /* .gwt-PopupPanelGlass is default style */

		zooming = false;
		card.addObserver(this);
		
		popup.addStyleName("zoomShell");
	}

	public boolean isZooming() {
		return zooming;
	}

	public void setZooming(boolean zooming) {
		this.zooming = zooming;
	}

	public void update(Observable o, Object arg) {
		ObservableLastMousedCard lastCard = (ObservableLastMousedCard) o;
		// System.out.println("[c] zoom-manager updating o: " + o);
		if(lastCard.hasCard()) { /* sometimes it can be, like when you put a card into a bin */
			DraggableCard card = ((ObservableLastMousedCard) o).getCard();

			String url = ((Image) popup.getWidget()).getUrl();

			/**
			 * quick check to make sure we're not updating the same card: url is in format
			 * http://localhost:8888/panda.PandaApp/cardsets/shm/75percent/202.jpg but card.getZoomUrl() will be
			 * /cardsets/shm/75percent/202.jpg, hence the contains() check
			 */
			if(!url.contains(card.getZoomUrl())) {
				/* if you don't own the card and it's face down, don't show the zoomed image */
				if(card.isFaceDown() && !card.isMine()) {
					replace(card, false);
				} else {
					replace(card, true);
				}
			}
		}
	}

	private void replace(DraggableCard card, boolean showCard) {
		if(showCard) {
			cardBackImg.setUrl(card.getZoomUrl());
		} else {
			cardBackImg.setUrl("img/cardback/cardback-100.jpg");
		}
	}

	public void show(DraggableCard card, boolean showCard) {
		setZooming(true);

		replace(card, showCard);
		popup.center();
	}

	public void hide() {
		popup.hide();
		setZooming(false);
	}
}